package com.gyms.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.gyms.R;
import com.gyms.bean.SetLocationBean;

import java.util.ArrayList;

/**
 * Created by ltx on 18/1/4
 * 设置收票地址的底部列表的adapter
 */

public class LocationListAdapter extends RecyclerView.Adapter<LocationListAdapter.LocationViewHolder> {
    private Context mContext;
    private ArrayList<SetLocationBean> mSetLocationBeans;//数据源
    public SetLocationBean mSelectedBean;//选中的Bean
    private boolean onBind;//解决更新checkBox 循环
    public LocationListAdapter(Context mContext,ArrayList<SetLocationBean> mSetLocationBeans){
        this.mContext=mContext;
        this.mSetLocationBeans=mSetLocationBeans;
    }
    @Override
    public LocationViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View mView= LayoutInflater.from(mContext).inflate(R.layout.ll_location_list_item,parent,false);
        return new LocationViewHolder(mView);
    }

    @Override
    public void onBindViewHolder(LocationViewHolder holder, int position) {
        SetLocationBean mSetLocationBean=mSetLocationBeans.get(position);
        holder.mTvLocationName.setText(mSetLocationBean.mPoiItem.getTitle());
        onBind = true;
        holder.mCbLocationSelected.setChecked(mSetLocationBean.isSelected);
        holder.mCbLocationSelected.setTag(position);
        onBind = false;
    }


    @Override
    public int getItemCount() {
        return null==mSetLocationBeans?0:mSetLocationBeans.size();
    }

     class LocationViewHolder extends RecyclerView.ViewHolder implements CompoundButton.OnCheckedChangeListener {
        private TextView mTvLocationName;
        private CheckBox mCbLocationSelected;
         LocationViewHolder(View itemView) {
            super(itemView);
            mCbLocationSelected= (CheckBox) itemView.findViewById(R.id.cb_location_selected);
            mTvLocationName= (TextView) itemView.findViewById(R.id.tv_location_name);
            mCbLocationSelected.setOnCheckedChangeListener(this);
        }

         @Override
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             if(onBind){
                return;
             }
             int mPos= (int) buttonView.getTag();
             if(isChecked&&null!=mSelectedBean){// 如果为true 清除当前的选中的bean
                 mSelectedBean.isSelected=false;
             }
             mSelectedBean=mSetLocationBeans.get(mPos);
             mSelectedBean.isSelected=isChecked;
             notifyDataSetChanged();
         }
     }
}
